package jsen.tool.ddd.adapter.infrastructure.specification.base;


import jsen.tool.ddd.adapter.infrastructure.specification.ISpecification;

import java.util.Map;
import java.util.function.Function;

/**
 * @author jsen
 * @date 2021/10/6
 */
class And<T> extends CompositeSpecification<T> {

    @Override
    @SuppressWarnings({"rawtypes", "unchecked"})
    public boolean isSatisfiedBy(SpecContext<T> t) {
        Map<CompositeSpecification<?>, Function<T, ?>> specificationMap = getSpecificationMap(t);
        if (specificationMap.isEmpty()) {
            return false;
        }
        boolean satisfied = true;
        for (Map.Entry<CompositeSpecification<?>, Function<T, ?>> entry : specificationMap.entrySet()) {
            ISpecification<?> spec = entry.getKey();
            Function<T, ?> change = entry.getValue();
            SpecContext<?> sub = t.subContext(change);
            if (!spec.isSatisfiedBy((SpecContext) sub)) {
                satisfied = false;
                if (SpecGlobalConfig.FAST_FAIL) {
                    return false;
                }
            }
        }
        return satisfied;
    }
}
